<?php
define('WEB_ROOT',dirname(__FILE__).DIRECTORY_SEPARATOR);
define('CFG_ROOT',dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR.'system'.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR);
@ini_set('memory_limit','64M');#设置内存大小
#图片路径
define('IMG_DIR',rtrim(WEB_ROOT,DIRECTORY_SEPARATOR));
//beansdb找不到图片是否输出原文件
define('IS_SHOW_FILE',false);
//加载失败时是否显示默认图片
define('IS_ERROR_IMG',true);
//beansdb服务设置
include_once CFG_ROOT.'file.inc.php';
global $cfg;
$cfg = $arrConfig['IMG_SERVER'];
//是否生成水印
$cfg['IS_WATER_IMG'] = true;
//是否读取本地图片
$cfg['IS_GET_LOCAL_IMG'] = false;
//设置生成图片使用类库(支持GD,IMAGICK)
$cfg['IMG_LIB']    = 'GD';
$cfg['IS_IMAGICK'] = false;
#$cfg['IMG_LIB'] = 'IMAGICK';
#$cfg['IS_IMAGICK'] = true;
#判断是否是动态图片 gif 邝达峰 添加
$imgInfo = pathinfo($_GET['img']);
$imgExt = $imgInfo['extension'];//后缀
$arrImg = explode('_',$imgInfo['basename'],2);

if(strtolower($imgExt) == 'gif')
{
	$cfg['IS_IMAGICK'] = true;
	$cfg['IS_WATER_IMG'] = false;
}
//水印图片文件
$cfg['water_img'] = array('images/water/wlogo.png','images/water/water_logo.png');
if (!$cfg['IS_IMAGICK']){
	$cfg['IMG_LIB'] = 'GD'; //默认为GD;
}
$ex          = explode('?',$_SERVER['REQUEST_URI']);
//路径替换
$_GET['img'] = str_replace('_test','',$_GET['img']);
#不需要打水印的目录
if(strpos($_GET['img'],'/uploads/llc/phb/') !== false) $cfg['IS_WATER_IMG'] = false;
elseif(strpos($_GET['img'],'/uploads/corp_quality_suppliers/') !== false) $cfg['IS_WATER_IMG'] = false;
elseif(strpos($_GET['img'],'/uploads/corp_banner/') !== false) $cfg['IS_WATER_IMG'] = false;
elseif(strpos($_GET['img'],'/uploads/aswords/') !== false) $cfg['IS_WATER_IMG'] = false;
elseif(strpos($_GET['img'],'/uploads/ggw/') !== false) $cfg['IS_WATER_IMG'] = false;
elseif(strpos($_GET['img'],'/uploads/spread/') !== false) $cfg['IS_WATER_IMG'] = false;
elseif(strpos($_GET['img'],'/uploads/city/') !== false) $cfg['IS_WATER_IMG'] = false;
elseif(strpos($_GET['img'],'/uploads/cp/') !== false) $cfg['IS_WATER_IMG'] = false;
elseif(strpos($_GET['img'],'/uploads/specialty/') !== false) $cfg['IS_WATER_IMG'] = false;
elseif(strpos($_GET['img'],'/uploads/life_classify/') !== false) $cfg['IS_WATER_IMG'] = false;
elseif(strpos($_GET['img'],'/uploads/corp_bg/') !== false) $cfg['IS_WATER_IMG'] = false;
elseif(strpos($_GET['img'],'/uploads/hetong/') !== false) {$cfg['IS_WATER_IMG'] = false;$cfg['IS_GET_LOCAL_IMG']=true;}
elseif(strpos($_GET['img'],'/uploads/add/') !== false) $cfg['IS_WATER_IMG'] = false;
elseif(strpos($_GET['img'],'/uploads/mobile/user/') !== false) $cfg['IS_WATER_IMG'] = false;
elseif(strpos($_GET['img'],'/uploads/mobile/img/') !== false) $cfg['IS_WATER_IMG'] = false;

//缩略图
if($arrImg[0] == 's' || $arrImg[0] == 'mini') //固定小图(100*100)
{
	$toW = 100;
	$toH = 100;
	$imgInfo['basename'] = $arrImg[1];
	$cfg['IS_WATER_IMG'] = false;
}elseif($arrImg[0] == 'm') //固定中图(280*280)
{
	$toW = 280;
	$toH = 280;
	$imgInfo['basename'] = $arrImg[1];
	$cfg['IS_WATER_IMG'] = false;
}elseif(strpos($imgInfo['basename'],'-')) {
	//判断是否使用图片自定义补白
	if($arrImg[0] == 'zf'){
		$imgInfo['basename'] = $arrImg[1];
		$cfg['IS_USE_FILLER'] = true;
	}else
	{
		$cfg['IS_USE_FILLER'] = false;
	}
	//动态大小
	$m = explode('-',preg_replace("/\.$imgExt.*$/",'',$imgInfo['basename']));
	if($m[1]) {
		$toW = intval($m[1]);
	}
	if($m[2]) {
		$toH = intval($m[2]);
	}
	//不生成水印
	if($m[3]) {
		$cfg['IS_WATER_IMG'] = false;
	}
	$imgInfo['basename'] = $m[0].'.'.$imgExt;
	unset($m);
}

#图片路径处理
$_GET['img_'] =$_GET['img'] ;
$_GET['img']  = $imgInfo["dirname"].'/'.$imgInfo['basename'];

#真实图片路径
$strRealPath = WEB_ROOT.$_GET['img'];

/**图片处理**/
include_once 'Flexihash.php';
$hash    = md5($_GET['img']);
$hash_   = md5($_GET['img_']);
$cache_serve  = Flexihash::intance()
->addTargets($cfg['CACHE'])
->lookupList($hash_,1);
$server       = explode(':',$cache_serve['0']);
$cache        = new Memcache;
$cache->addServer($server[0],$server[1]);
if($ex['1']=='del'){
	$cache->delete($hash_);
	exit;
}
$data   = $cache->get($hash_);
if($data){
	set_header($imgExt);
	writ_redis_log($hash_);
	exit($data);
}
$sinfo = get_beansdb($ex['0'],$cfg);
if(!$data){
	if($sinfo['time']&&(time()-$sinfo['time'])<3600 * 24 * 5){
		$redis = new redis();
		$red   = explode(':',$cfg['REDIS']['READ']['0']);
		$redis->connect($red['0'],$red['1']);
		$data  = $redis->get($hash);
		//--判断redis 缓存图片真实路径 邝达峰
		if(REDIS_IMAGE_SEP){
			if($data){
				$arrData = explode(REDIS_IMAGE_SEP,$data);
				$data = $arrData[count($arrData)-1];
			}
		}
		//--------
	}
}
//最终存储路径
if(!$data){
	$is_succ = false;
	$beansdb = new Memcache;
	foreach($sinfo['server'] as $k=>$s){
		$bdb  = explode(':',$s);
		$is_succ  = $beansdb->addServer($bdb[0],$bdb[1]);
		if($is_succ) {
			$data = $beansdb->get(md5($_GET['img']));
			if($data){ break;}
		}
	}
}

#如果是图片文件形式保存
if($cfg['IS_GET_LOCAL_IMG']===true){
	if(file_exists($strRealPath)){
		$data = file_get_contents($strRealPath);
	}
}

if($data){
	writ_redis_log($hash_);
	/**判断是否使用Gmagick插件处理图片**/
	if($cfg['IMG_USE_GMAGICK'] && strtolower($imgExt) != 'gif' ){
		$arrImageInfo = array('toW'=>$toW,'toH'=>$toH,'ext'=>$imgExt,'hash'=>$hash_,'cache'=>$cache,'fillerStatus'=>$cfg['IS_USE_FILLER']);
		exe_gmagick_img($data,$arrImageInfo);
	}
	/*******************************/
	//gif动画使用 IMAGICK处理,其它使用默认设置
	if ($GLOBALS['cfg']['IS_IMAGICK'] && strtolower($imgExt) == 'gif' && $GLOBALS['cfg']['IMG_LIB'] == 'GD' && strpos($data,'GIF') === 0) {
		$GLOBALS['cfg']['IMG_LIB'] = 'IMAGICK';
	}
	if($GLOBALS['cfg']['IMG_LIB'] == 'IMAGICK'){
		$im = new Imagick();
		$im->readImageBlob($data);
	}else{
		$im = @imagecreatefromstring($data);
	}
}elseif(IS_SHOW_FILE){
	if($GLOBALS['cfg']['IMG_LIB'] == 'IMAGICK'){
		$im = new Imagick(IMG_DIR.$_GET['img']);
	}else{
		$im = loadImg(IMG_DIR.$_GET['img']);
	}
}
ob_start();
exe_img($im);
$img = ob_get_contents();
ob_end_clean();
$cache->set($hash_,$img,false);
set_header($imgExt);
echo $img;
/**
 * $img :图片路径 ...../s_x1_1.1348014868_31_31_2608.gif
 * $conf :服务器配置文件
 * */
function  get_beansdb($img,$conf){
	$info = pathinfo($img);
	$exd  = explode('.',$info['basename']);
	if($exd['2']){
		$cons  = explode('_',$exd['0']);
		$cons2 = explode('_',$exd['1']);
		$res['type']  = '1';
		$res['time']  = $cons2['0'];
		if($cons['2']){
			$res['loc']   = $cons['2'];
			$res['pre']   = $cons['1'];
			$res['server'][]= $conf['CONFG'][$cons['1']];
		}else{
			$res['loc']   = $cons['1'];
			$res['pre']   = $cons['0'];
			$res['server'][]= $conf['CONFG'][$cons['0']];
		}
	}else{
		$res['pre']   = 'default';
		$res['loc']   = '';
		$res['type']  = '0';
		$res['server']= $conf['CONFG']['default'];
	}
	return $res;
}

function set_header($imgExt){
	$imgExt = strtolower($imgExt);
	if($imgExt == 'jpg'){
		header("Content-Type: image/jpeg");
	} else{
		header("Content-Type: image/$imgExt");
	}
	header("Last-Modified: " . date("D, d M Y H:i:s",time()-24*3600*7) . " GMT");
}
function writ_redis_log($hash){
	//暂时去掉图片日志缓存
	return true;
	global $cfg;
	$s  = explode(':',$cfg['REDISLOG']['0']);
	$redis2 = new Redis();
	$redis2->connect($s[0],$s[1]);
	$redis2->set($hash,time());
}
function exe_img($im){
	global $toW,$toH,$cfg;
	if(!$im){
		header("Content-Type: image/jpg");
		header("HTTP/1.1 404 Not Found");
		ob_end_clean();
		exit;
	}

	if($toW || $toH){
		if($GLOBALS['cfg']['IMG_LIB'] == 'IMAGICK'){
			$srcW=$im->getImageWidth();
			$srcH=$im->getImageHeight();
		}else{
			$srcW=imagesx($im);
			$srcH=imagesy($im);
		}

		if(!$toW) {
			$toW = $srcW;
		}
		if(!$toH) {
			$toH = $srcH;
		}

		//判断自定义大小是否大于原图
		if($srcW<=$toW)
		{
			$toW = $srcW;
		}

		if($srcH<=$toH)
		{
			$toH = $srcH;
		}

		$toWH=$toW/$toH;
		$srcWH=$srcW/$srcH;
		if($toWH<=$srcWH){
			$ftoW=$toW;
			$ftoH=$ftoW*($srcH/$srcW);
		}else{
			$ftoH=$toH;
			$ftoW=$ftoH*($srcW/$srcH);
		}
		//处理自定义图片
		if($srcW>=$toW||$srcH>=$toH){
			if($GLOBALS['cfg']['IMG_LIB'] == 'IMAGICK'){
				foreach ($im as $frame){
					$frame->thumbnailImage($ftoW, $ftoH);
					$frame->setImagePage($ftoW, $ftoH, 0, 0);
					if ($GLOBALS['cfg']['IS_WATER_IMG']){
						$frame = water($frame);
					}
				}//
				echo $im->getImagesBlob();
			}else{
				if(function_exists("imagecreatetruecolor")){
					@$ni = imagecreatetruecolor($ftoW,$ftoH);
					if($ni){
						imagecopyresampled($ni,$im,0,0,0,0,$ftoW,$ftoH,$srcW,$srcH);
					}else{
						$ni=imagecreate($ftoW,$ftoH);
						imagecopyresized($ni,$im,0,0,0,0,$ftoW,$ftoH,$srcW,$srcH);
					}
				}else{
					$ni=imagecreate($ftoW,$ftoH);
					imagecopyresized($ni,$im,0,0,0,0,$ftoW,$ftoH,$srcW,$srcH);
				}

				if ($cfg['IS_WATER_IMG'] && $ni){
					$ni = water($ni);
				}
				if(function_exists('imagejpeg')){
					if(!imagejpeg($ni)){
						imagejpeg($im);
					}
				}elseif(function_exists('imagegif')){
					if(!imagegif($ni)) {
						imagegif($im);
					}
				}elseif(!imagepng($ni)){
					imagepng($im);
				}
			}
		}
	}else{
		if($GLOBALS['cfg']['IMG_LIB'] == 'IMAGICK'){
			echo @$im->getImagesBlob();
		}else{
			if ($cfg['IS_WATER_IMG']) $im = water($im);
			if(function_exists('imagejpeg')) {
				imagejpeg($im);
			}elseif(function_exists('imagegif')){
				imagegif($im);
			}else{
				imagepng($im);}
		}
	}
}

//生成水印
function water($im)
{
	if($GLOBALS['cfg']['IMG_LIB'] == 'IMAGICK')
	{
		$srcW=$im->getImageWidth();
		$srcH=$im->getImageHeight();
		$waterImage = new Imagick(WEB_ROOT.$GLOBALS['cfg']['water_img'][0]);
		$waterW=$waterImage->getImageWidth();
		$waterH=$waterImage->getImageHeight();
	}
	else
	{
		imagealphablending($im, true);
		$srcW=imagesx($im);
		$srcH=imagesy($im);

		$waterImage = loadImg(WEB_ROOT.$GLOBALS['cfg']['water_img'][0]);
		$waterW=imagesx($waterImage);
		$waterH=imagesy($waterImage);
	}
	//太小的图片不生成水印
	if($srcW < $waterW || $srcH < $waterH || ($srcW < $waterW * 4 && $srcH < $waterH * 4)) return $im;
	//底端居右
	$waterPosX = $srcW - $waterW * rand(115,120) / 100;
	$waterPosY = $srcH - $waterH * rand(115,120) / 100;
	//透明度
	if($GLOBALS['cfg']['IMG_LIB'] == 'IMAGICK')
	{
		$pct = 0.5;
		$waterImage->evaluateImage(Imagick::EVALUATE_MULTIPLY,$pct,Imagick::CHANNEL_ALPHA);
		foreach ($im as $frame)
		{
			$frame->compositeImage($waterImage, Imagick::COMPOSITE_DEFAULT, $waterPosX, $waterPosY);
		}
	}else{
		$pct = 35;
		//生成水印
		$cut = imagecreatetruecolor($srcW, $srcH);
		imagecopy($cut, $im, 0, 0, $waterPosX, $waterPosY, $waterW, $waterH);
		imagecopy($cut, $waterImage, 0, 0, 0, 0, $waterW, $waterH);
		imagecopymerge($im, $cut, $waterPosX, $waterPosY, 0, 0, $waterW, $waterH, $pct);
	}
	return $im;
}

//读取图片
function loadImg($img)
{
	$data = @getimagesize($img);
	if(!$data) return false;
	switch ($data[2])
	{
		case 1:
			if(!function_exists("imagecreatefromgif")) exit;
			$im = imagecreatefromgif($img);
			break;
		case 2:
			if(!function_exists("imagecreatefromjpeg")) exit;
			$im = imagecreatefromjpeg($img);
			break;
		case 3:
			$im = imagecreatefrompng($img);
			break;
	}
	return $im;
}



/**
 *执行Gmagick插件处理图片
 *@param $data 图片二进制源
 *@param $arrImgInfo 图片信息
 *@author 邝达峰
 */
function exe_gmagick_img($data,$arrImgInfo){
	if(!empty($data)){
		ob_start();
		$hash = $arrImgInfo['hash'];//哈希值
		$cache = $arrImgInfo['cache'];//缓存对象
		#需要处理图片的信息
		$toW = $arrImgInfo['toW'];//处理图片的宽度
		$toH = $arrImgInfo['toH'];//处理图片的宽度
		$imgExt = $arrImgInfo['ext'];//处理图片类型

		$gmagick = new Gmagick();//创建图片对象
		$gmagick->readImageBlob($data);//通过图片源读取图片
		$srcW=$gmagick->getImageWidth();//原图宽度
		$srcH=$gmagick->getImageHeight();//原图高度
		$toW = ($toW > $srcW) ? $srcW : $toW;
		$toH = ($toH > $srcH) ? $srcH : $toH;
		#处理图片高度和宽度
		$toW = $toW?$toW:$srcW;
		$toH = $toH?$toH:$srcH;
		if($toW < 10){$toW = $srcW;}
		if($toH < 10){$toH = $srcH;}
		//$gmagick->cropthumbnailimage(400,400);//切割图片
		//$gmagick->thumbnailimage($toW,$toH,true);//按比例缩小图片
		$gmagick->resizeImage($toW, $toH, Gmagick::FILTER_LANCZOS, 1, true);
		//$gmagick->resizeImage(200, 900, Gmagick::FILTER_LANCZOS, 1, true);
		$gmagick->setCompressionQuality(95);//控制图片质量
		/**进行水印操作**/
		if ($GLOBALS['cfg']['IS_WATER_IMG']){
			$waterImage = new Gmagick();
			$waterImage->readimage(WEB_ROOT.$GLOBALS['cfg']['water_img'][1]);
			$waterW=$waterImage->getImageWidth();//水印宽度
			$waterH=$waterImage->getImageHeight(); //水印高度
			#水印底端居右
			$thumbW=$gmagick->getImageWidth();//处理后图宽度
			$thumbH=$gmagick->getImageHeight();//处理后图高度
			$waterPosX = $thumbW - $waterW * rand(115,120) / 100;
			$waterPosY = $thumbH - $waterH * rand(115,120) / 100;
			#太小的图片不生成水印
			if(!($thumbW < $waterW || $thumbH < $waterH || ($thumbW < $waterW * 4 && $thumbH < $waterH * 4))) {
				$gmagick->compositeimage($waterImage, Gmagick::COMPOSITE_DEFAULT, $waterPosX, $waterPosY);
			}
		}
		/*************/
		if(!empty($arrImgInfo['toW']) && !empty($arrImgInfo['toH']) && $arrImgInfo['fillerStatus']==true)
		{
			/*背景空白填充处理 start**/
			$backgroudImage = new Gmagick();
			$backgroudImage->newimage($arrImgInfo['toW'],$arrImgInfo['toH'],"#fff",'jpg');
			$customW = $arrImgInfo['toW'];
			$customH = $arrImgInfo['toH'];
			$backgroudX = intval(($customW-$gmagick->getImageWidth())/2);
			$backgroudY = intval(($customH-$gmagick->getImageHeight())/2);
			$backgroudImage->compositeimage($gmagick, Gmagick::COMPOSITE_DEFAULT, $backgroudX, $backgroudY);
			/*背景空白填充处理 end**/
			$outputImage = $backgroudImage->getImageBlob();//获取补白图片源
		}else
		{
			$outputImage = $gmagick->getImageBlob();//获取正确图片图片源
		}
		/**销毁对象*/
		$gmagick->destroy();
		#输出图片操作
		echo $outputImage;
		$img = ob_get_contents();
		ob_end_clean();
		if ($GLOBALS['cfg']['IS_GET_LOCAL_IMG']===false)
		{
			$cache->set($hash,$img,false);//缓存处理
		}
		set_header($imgExt);//设置图片头部
		echo $img;//输出图片
		exit();
	}
}
?>
